/*
	Focus core functionality
	----------------------------------------------------------------
*/
	/*
		Global constants
		------------------------------------------------------------
	*/
		// Do not modify! Will be assigned during page load.
		var BASE_URL;
	
	/*
		Objects
		------------------------------------------------------------
	*/
	
	/*
		Ajax
		------------------------------------------------------------
	*/

		function login()
		{
			if( validate_auth_form() )
			{
				$.post('/api/login', $('#auth-form').serialize(), function(data)
				{
					var response = jQuery.parseJSON(data);
					console.log(response);
					
					if(response.result == 0)
					{
						showMessage('Vale kasutajatunnus ja / või parool!');
					}
					else
					{
						showMessage('Login sisse...');
						setTimeout(function () {
							goHome();
						}, 1500);
					}
				});
			}
		}
		
		function signup()
		{
			var redisable = false;
			
			if( validate_auth_form() )
			{
				if($('input[name=email]').attr('disabled'))
				{
					$('input[name=email]').attr('disabled', false);
					redisable = true;
				}

				$.post('/api/signup', $('#auth-form').serialize(), function(data)
				{
					if(redisable)
						$('input[name=email]').attr('disabled', true);
					
					var response = jQuery.parseJSON(data);
					console.log(response);
					
					if(response.result == -1)
					{
						showMessage('Vigane e-posti aadress!');
						console.log(response.extra);
					}
					else if(response.result == 0)
					{
						showMessage('Selline e-posti aadress on juba kasutusel!');
					}
					else if(response.result == 1)
					{
						showMessage('Registreeritud! Login sisse...');
						setTimeout(function () {
							goHome();
						}, 1500);
					}
				});
			}
		}
	
	/*
		Utils
		------------------------------------------------------------
	*/
	
		function goHome()
		{
			window.location = BASE_URL;
		}
		
		function validate_auth_form()
		{
			if( $('#auth-form').length )
			{
				if ( ($('input[name=email]').val().length) && ($('input[name=password]').val().length) )
				{
					return true;
				}
				else
				{
					showMessage('Email ja / või parool sisestamata!');
				}
			}
			
			return false;
		}
		
		function showMessage(message)
		{
			humanMsg.displayMsg(message);
		}
		
	/*
		UI & Effetcs
		------------------------------------------------------------
	*/
	
		// jQuery Center plugin
		(function($){
			$.fn.extend({
				center: function () {
					return this.each(function() {
						var top = ($(window).height() - $(this).outerHeight() - $('#navigation-bar-container').height()) / 2;
						var left = ($(window).width() - $(this).outerWidth()) / 2;
						$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
					});
				}
			}); 
		})(jQuery);
		
		// Sidebar functions
		function hide_top_sidebar()
		{
			$('#top-sidebar-content').hide();
		}
		
		function show_hide_top_sidebar()
		{
			
			
			if($('#top-sidebar-content').is(':visible'))
			{
				$('#top-sidebar-handle').css('background-image', 'url(' + BASE_URL + 'img/drop-handle-down.png)')
				$('#top-sidebar-content').slideUp(500);
				$('#top-sidebar-content').unbind('mouseleave');
			}
			else
			{
				$('#top-sidebar-handle').css('background-image', 'url(' + BASE_URL + 'img/drop-handle-up.png)')
				$('#top-sidebar-content').slideDown(500);
				setTimeout(function()
				{
					// Attach mouse-out
					$('#top-sidebar-content').mouseleave(function(e) {
						show_hide_top_sidebar();
					});
					
					// If user clicks somewhere in $('#top-sidebar-content')
					// (a strong indication that he/she is about to submit sth),
					// unbind slide up. 
					$('#top-sidebar-content').click(function(e) {
                        $('#top-sidebar-content').unbind('mouseleave');
                    });
				},
				500);
			}
		}
		
		// Slides up every category except '.active' one
		function right_navig_slide()
		{
			$('ul[class=right-navig]').each(function(index, element) {
                if( !$(element).children('.active').length )
				{
					$(element).children('li[class=item]').each(function(index, element) {
                     		$(element).hide(); 	  
                    });
				}
				else
				{
					$(element).children('li[class=item]').each(function(index, element) {
                     		$(element).show(); 	  
                    });
				}
            });
		}
		
		// Attach Click Event handler to categories
		function right_navig_attach_click()
		{
			$('ul[class=right-navig]').each(function(index, element) {
				$(element).children('.category').first().click(function(e) {
                    if($(this).hasClass('active'))
					{
						$(this).removeClass('active');
					}
					else
					{
						// Find previous active category and remove class
						$('ul[class=right-navig]').each(function(index, element) {
							if($(element).children('.active').length)
							{
								$(element).children('.active').removeClass('active');
							}
						});
						
						$(this).addClass('active');
					}
					
					right_navig_slide();
                });
			});
		}
		
		
		// Init right menu
		function init_right_navig()
		{
			$('ul[class=right-navig]').first().children('li[class=category]').first().addClass('active')
			
			right_navig_slide();
			right_navig_attach_click();
		}
		
		// Balance content container heights
		function balance_left_right_containers()
		{
			if($('.right-content').length && $('.left-content').length)
			{
				$('.right-content').css('height', $('.left-content').height() + 5);
			}
		}

	/*
		Document ready
		------------------------------------------------------------
	*/
	$(document).ready(function(e) {
		
		/*
			UI & Effetcs
			------------------------------------------------------------
		*/
		
		// Hide top sidebar
		hide_top_sidebar();
		
		// Attach event handler to handle
		$('#top-sidebar-handle').click(function(e) {
            show_hide_top_sidebar();
        });
		
		// Center Demo-banner
		if($('.demo-banner').length)
		{
			$('.demo-banner').center();
			$('#demo-banner-content').coinslider({
				width: 980,
				height: 420,
				spw: 7,
				sph: 5, 
				delay: 3000,
				sDelay: 30,
				opacity: 0.7,
				titleSpeed: 500,
				effect: 'random', // random, swirl, rain, straight
				navigation: false,
				links : false, // show images as links
				hoverPause: true // pause on hover
			});
		}
		
		// Collapse all but first
		init_right_navig();
		
		// Balance content container heights
		balance_left_right_containers();
		
		/*
			Events
		*/
		
		// Trigger Sidebar Handle click on Auth page
		$('#btn-main-auth').click(function(e) {
            $('#top-sidebar-handle').trigger('click');
        });
		
		
		// Navigate home
		$('#logo').click(function(e) {
            goHome();
        });
		
		
		// Ajax login
		$('#login-btn').click(function(e) {
            login();
        });
		
		// Ajax signup
		$('#signup-btn').click(function(e) {
            signup();
        });
		
	});